package com.ruoyi.jiekou.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONValidator;
import com.br.client.facade.MerchantServer;
import com.juhe.sdk.ApiClient;
import com.juhe.sdk.common.Result;
import com.juhe.sdk.reqeust.BaseRequest;
import com.juhe.sdk.reqeust.PersonalRentScoreRequest;
import com.juhe.sdk.reqeust.StudentVerifyRequest;
import com.juhe.sdk.response.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.http.JuFaHttp;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.finance.domain.ChargeRecord;
import com.ruoyi.finance.domain.Merchant;
import com.ruoyi.finance.service.IMerchantService;
import com.ruoyi.jiekou.domain.InterPrice;
import com.ruoyi.jiekou.domain.JieKou;
import com.ruoyi.jiekou.domain.ProductDto;
import com.ruoyi.jiekou.domain.YushanAES;
import com.ruoyi.jiekou.mapper.InterPriceMapper;
import com.ruoyi.jiekou.mapper.JieKouMapper;
import com.ruoyi.jiekou.service.IJieKouService;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static com.ruoyi.common.constant.Constants.UTF8;
import static com.ruoyi.common.utils.ZeWu.getResult;
import static com.ruoyi.common.utils.http.HttpUtils.dataPost;

@Service
@Slf4j
public class JieKouServiceImpl implements IJieKouService {

    public static String TEST_URI = "http://122.152.195.249:21000/credit-gw/service";

    public static String LOCAL_URI = "https://api.yushanshuju.com/credit-gw/service";

    public static String ACCOUNT_ID = "scxdjk_main";

    public static String HEX_AES_128_PASSWORD = "54545570615230524353567050513056";

    public static String[] tollCodes = {"warn_002", "warn_003", "warn_004", "warn_310", "warn_311", "warn_312", " warn_315", "warn_316", "000000", "100000"};

    @Value("${credit.notifyUrl}")
    private String notifyUrl;

    @Autowired
    private JieKouMapper jieKouMapper;

    @Autowired
    private InterPriceMapper interPriceMapper;

    @Autowired
    private IJieKouService jieKouService;

    @Autowired
    private IMerchantService iMerchantService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public JieKou getUserInterPrice(String merchantCode, String jfCode) {
        List<InterPrice> interPrices = interPriceMapper.selectInterPriceList(new InterPrice(merchantCode, jfCode));
        JieKou jieKou = jieKouMapper.selectJieKouOne(new JieKou(jfCode, null));
        if (interPrices == null || jieKou == null) {
            return null;
        } else if (interPrices.size() == 0) {
            return jieKou;
        } else {
            jieKou.setUnitPrice(interPrices.get(0).getPrice());
            return jieKou;
        }
    }

    @Override
    public JieKou selectJieKouByjfCode(String jfCode) {
        JieKou jieKou = new JieKou();
        jieKou.setJfCode(jfCode);
        return jieKouMapper.selectJieKouOne(jieKou);
    }

    @Override
    public List<JieKou> selectJieKouList(JieKou jieKou) {
        return jieKouMapper.selectJieKouList(jieKou);
    }

    @Override
    public int updateJieKou(JieKou jieKou) {
        jieKou.setUpdateTime(DateUtils.getNowDate());
        return jieKouMapper.updateJieKou(jieKou);
    }

    public static void makeAccredit(String name, String cardNo, String mobile, String fileCode) {
        Document doc = new Document();
        Resource resource = new ClassPathResource("授权书_模板" + fileCode + ".docx");
        try {
            doc.loadFromStream(resource.getInputStream(), FileFormat.Docx);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("${name}", name);
        map.put("${cardNo}", cardNo);
        map.put("${mobile}", StringUtils.isEmpty(mobile) ? "" : mobile);
        map.put("${sqname}", name);
        map.put("${date}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd hh:mm")));
        // 正则表达式，匹配所有的占位符 ${}
        Pattern pattern = Pattern.compile("\\$\\{.*?}");
        // 根据正则表达式获取所有文本
        TextSelection[] allPattern = doc.findAllPattern(pattern);
        // 逐个替换占位符
        for (TextSelection textSelection : allPattern) {
            String tmp = map.get(textSelection.getSelectedText());
            doc.replace(textSelection.getSelectedText(), tmp, true, true);
        }
        // 保存为文件
        doc.saveToFile("授权书" + fileCode + ".docx", FileFormat.Docx);
    }

    @Override
    public JSONObject select(JSONObject req_params, Merchant merchant, JieKou jieKou, String requestSn) {
        // 提取关键字下发查询
        JSONObject reJs = new JSONObject();
        String cardNo = null, name = null, mobile = null, pageNo, pageSize;
        StringBuffer keyWord = new StringBuffer();
        Map<String, Object> source1And2Params = new HashMap<>();
        JSONObject source4Params = new JSONObject();
        if (req_params.containsKey("cardNo")) {
            cardNo = req_params.getString("cardNo");
            source1And2Params.put("cardNo", cardNo);            // 身份证号
            keyWord.append("::" + cardNo);
            source4Params.put("cert_no", cardNo);
        }
        if (req_params.containsKey("name")) {
            name = req_params.getString("name");
            source1And2Params.put("name", name);
            source4Params.put("cert_name", name);
            keyWord.append("::" + name);
        }
        if (req_params.containsKey("mobile")) {
            mobile = req_params.getString("mobile");
            source1And2Params.put("mobile", mobile);
            source4Params.put("mobile", mobile);
            keyWord.append("::" + mobile);
        }
        if (req_params.containsKey("pageNo")) {
            pageNo = req_params.getString("pageNo");
            source1And2Params.put("pageNo", pageNo);
            keyWord.append("::" + pageNo);
        }
        if (req_params.containsKey("pageSize")) {
            pageSize = req_params.getString("pageSize");
            source1And2Params.put("pageSize", pageSize);
            keyWord.append("::" + pageSize);
        }
        if (req_params.containsKey("photo")) {
            source1And2Params.put("photo", req_params.get("photo"));
        }
        if (jieKou.getSfCode().contains("credit")) {
            source4Params.put("id_card_front", req_params.getString("idCardFront"));
            source4Params.put("id_card_reverse", req_params.getString("idCardReverse"));
            source4Params.put("hand_id_card", req_params.getString("handIdCard"));
            source4Params.put("power", req_params.getString("power"));
            source4Params.put("type", req_params.getString("type"));
            source4Params.put("purpose", "1");
            source4Params.put("notify_url", notifyUrl);    // 此处回调
        }
        if (jieKou.getSourceTypeNum() == 1) {   // 指向的查询数据源均为yushan
            if ("RIS005".equals(jieKou.getSfCode())) {      // 小部分接口调用参数特殊
                source1And2Params.replace("cardNo", Md5Utils.hash((String) source1And2Params.get("cardNo")));
                source1And2Params.replace("mobile", Md5Utils.hash((String) source1And2Params.get("mobile")));
            }
            reJs = jieKouService.yuShan(source1And2Params, jieKou.getJfCode() + keyWord, jieKou.getSfCode(), requestSn);
            reJs = disposeYuShanReturnData(reJs, false);
            // 扣费信息
            ChargeRecord cr = new ChargeRecord(merchant.getMerchantCode(), requestSn, reJs.getString("response_sn"),
                    jieKou.getName(), keyWord.toString(), reJs.toJSONString(), jieKou.getUnitPrice());
            BigDecimal subtract = merchant.getBalance().subtract(jieKou.getUnitPrice());
            cr.setBalance(subtract);
            cr.setCostResult("收费成功");
            iMerchantService.debit(new Merchant(merchant.getMerchantCode(), jieKou.getUnitPrice()), cr);
            return reJs;
        } else if (jieKou.getSourceTypeNum() == 2) {    // 指向的查询数据源均为baiRong
            reJs = jieKouService.baiRong(source1And2Params, jieKou.getJfCode() + keyWord, requestSn);
            reJs = disposeBaiRongReturnData(reJs, requestSn, true);
        } else if (jieKou.getSourceTypeNum() == 3) {
            reJs = selectQwd(req_params, requestSn);
            ChargeRecord cr = new ChargeRecord(
                    merchant.getMerchantCode(),
                    requestSn,
                    jieKou.getName(),
                    keyWord.toString(),
                    reJs.toJSONString(),
                    jieKou.getUnitPrice(),
                    merchant.getBalance().subtract(jieKou.getUnitPrice()),
                    reJs.getString("allMsg")
            );
//            reJs.remove("allMsg");
            iMerchantService.debit(new Merchant(merchant.getMerchantCode(), jieKou.getUnitPrice()), cr);
            return reJs;
        } else if (jieKou.getSourceTypeNum() == 4) {                // 指向的查询数据源均为则悟（左科）
            String sfCode = jieKou.getSfCode();
            String jfCode = jieKou.getJfCode();
            String type = "JF020".equals(jfCode) || "JF023".equals(jfCode) ? "1" : null;
            type = "JF015".equals(jfCode) ? "2" : "JF016".equals(jfCode) ? "3" : "JF017".equals(jfCode) ? "4" : type;
            keyWord.insert(0, sfCode + (type != null ? type : ""));

            reJs = jieKouService.zeWu(jieKou, type, source4Params, jieKou.getJfCode() + keyWord);
            // 针对credit添加回调
            if (jieKou.getSfCode().contains("credit") && reJs.getInteger("code") == 0) {
                String order_no = reJs.getJSONObject("data").getString("order_no");
                redisTemplate.boundValueOps(order_no).set(req_params.getString("notifyUrl"), 1, TimeUnit.HOURS);
            }
            reJs = disposeZewuReturnData(reJs, requestSn, true);
        } else if (jieKou.getSourceTypeNum() == 5) {                // 指向的查询数据源均为巨合
            if ("A1".equals(jieKou.getSfCode()) || "A2".equals(jieKou.getSfCode()) || "A4".equals(jieKou.getSfCode())) {
                StudentVerifyRequest param = new StudentVerifyRequest();
                param.setIdCardNo(cardNo);
                param.setFullName(name);
                reJs = juHe(jieKou, param, jieKou.getJfCode() + keyWord);
            } else if ("A5".equals(jieKou.getSfCode())) {
                BaseRequest param = new BaseRequest();
                reJs = juHe(jieKou, param, jieKou.getJfCode() + keyWord);
            } else {
                PersonalRentScoreRequest param = new PersonalRentScoreRequest();
                param.setIdCardNo(cardNo);
                param.setFullName(name);
                param.setMobile(mobile);
                param.setFileId("");
                reJs = juHe(jieKou, param, jieKou.getJfCode() + keyWord);
            }
            reJs = disposeJuHeReturnData(reJs, requestSn, true);
        } else if (jieKou.getSourceTypeNum() == 6) {                // 指向的查询为编号6数据源
            JSONObject reqData = new JSONObject();
            reqData.put("nameKey", "ahieXNI614");
            reqData.put("secretKey", "bxCRw164MAPS3/?*26SWns/vpz\\GDfe");
            reqData.put("requestId", requestSn);
            // 生成授权书
            makeAccredit(name, cardNo, mobile, "2");
            // 添加授权书url
            reqData.put("accessoryUrl", "http://jiekou.funishe.com/prod-api/jiekou/accredit/2");
            reqData.put("userName", name);
            reqData.put("idNumber", cardNo);
            reqData.put("phoneNumber", mobile);
            reqData.put("sign", com.br.client.util.Md5Utils.genMd5("ahieXNI614" + name + cardNo + "bxCRw164MAPS3/?*26SWns/vpz\\GDfe" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))));
            reJs = sourceTypeNum6(jieKou, reqData, jieKou.getJfCode() + keyWord);
            // 扣费信息
            reJs = disposeSourceTypeNum6ReturnData(reJs, requestSn, true);
        } else if (jieKou.getSourceTypeNum() == 7) {                // 指向的查询为编号7数据源
            reJs = zeWu2(jieKou, req_params, jieKou.getJfCode() + keyWord);
            reJs = disposeYuxinReturnData(reJs, requestSn, true);
        } else if (jieKou.getSourceTypeNum() == 8) {                // 指向的查询为编号8数据源
            reJs = beiBuWan(jieKou, req_params, jieKou.getJfCode() + keyWord,  requestSn);

            if ("JF007".equals(jieKou.getJfCode())) {
                System.out.println("-JF007：" + reJs.toJSONString());
            } else if ("JF005".equals(jieKou.getJfCode())) {
                System.out.println("-JF005：" + reJs.toJSONString());
            }

            reJs = disposeBeiBuWan(reJs, requestSn, true);

            if ("JF007".equals(jieKou.getJfCode())) {
                System.out.println("-JF007-：" + reJs.toJSONString());
                reJs = beiBuWanThreeEleConversion(reJs);
                System.out.println("-JF007Conversion-：" + reJs.toJSONString());
            } else if ("JF005".equals(jieKou.getJfCode())) {
                System.out.println("-JF005-：" + reJs.toJSONString());
                reJs = beiBuWanTwoEleConversion(reJs);
                System.out.println("-JF005Conversion-：" + reJs.toJSONString());
            }
        }
        // 扣费信息
        ChargeRecord cr = new ChargeRecord(
                merchant.getMerchantCode(),
                requestSn,
                reJs.getString("response_sn"),
                jieKou.getName(),
                keyWord.toString(),
                reJs.toJSONString(),
                jieKou.getUnitPrice()
        );
        BigDecimal subtract = merchant.getBalance().subtract(jieKou.getUnitPrice());
        cr.setBalance(subtract);
        cr.setCostResult("收费成功");
        iMerchantService.debit(new Merchant(merchant.getMerchantCode(), jieKou.getUnitPrice()), cr);
        return reJs;
    }

    public JSONObject selectQwd(JSONObject req_params, String requestSn) {
        JSONObject repData = new JSONObject();
        repData.put("request_sn", requestSn);
        JSONObject retData = new JSONObject();
        StringBuffer allMsg = new StringBuffer();
        // 提取关键字下发查询

        String cardNo = req_params.getString("cardNo");
        String name = req_params.getString("name");
        String mobile = req_params.getString("mobile");
        JSONObject ncParams = new JSONObject();
        ncParams.put("name", name);
        ncParams.put("cardNo", cardNo);
        String ncKeyWord = "::" + cardNo + "::" + name;

        JSONObject ncmParams = new JSONObject();
        ncmParams.put("name", name);
        ncmParams.put("cardNo", cardNo);
        ncmParams.put("mobile", mobile);
        String ncmKeyWord = "::" + cardNo + "::" + name + "::" + mobile;

        JSONObject cmParams = new JSONObject();
        cmParams.put("cardNo", cardNo);
        cmParams.put("mobile", mobile);
        String cmKeyWord = "::" + cardNo + "::" + mobile;

        JSONObject mParams = new JSONObject();
        mParams.put("mobile", mobile);
        String mKeyWord = "::" + mobile;
        // 1：实名认证
        JSONObject smrz = jieKouService.yuShan(ncParams, "JF005" + ncKeyWord, "PCB008", requestSn + "JF005");
        allMsg.append("实名认证:" + smrz.getString("retmsg"));
        repData.put("autonymCode", smrz.getString("retcode"));
        retData.put("autonym", disposeYuShanReturnData(smrz, true));
        // 2：手机号在网时间+手机三要素信息核验API
        // 2-1 手机三要素信息核验API
        JSONObject sjsys = jieKouService.yuShan(ncmParams, "JF007" + ncmKeyWord, "PCB151", requestSn + "JF007");
        allMsg.append(" 手机三要素:" + sjsys.getString("retmsg"));
        repData.put("phoneVerificationCode", sjsys.getString("retcode"));
        retData.put("phoneVerification", disposeYuShanReturnData(sjsys, true));

        // 2-2 手机号在网时间-- TelOnlineQuery
        JSONObject telOnline = jieKouService.yuShan(mParams, "JF030" + mKeyWord, "MOB016", requestSn + "JF030");
        String retcode = telOnline.getString("retcode");
        if ("000000".equals(retcode) || "000001".equals(retcode) || "000002".equals(retcode) || "000003".equals(retcode)) {
            telOnline.replace("retcode", "000000");
            redisTemplate.boundValueOps("JF030" + mKeyWord).set(telOnline.toJSONString(), 3, TimeUnit.DAYS);
        }
        allMsg.append(" 在网时间:" + telOnline.getString("retmsg"));
        repData.put("telOnlineTomeCode", telOnline.getString("retcode"));
        retData.put("telOnlineTome", disposeYuShanReturnData(telOnline, true));
        // 可信度查询V3
        JSONObject riskList = jieKouService.yuShan(ncParams, "JF002" + ncKeyWord, "HRD016", requestSn + "JF002");
        allMsg.append(" 风险名单:" + riskList.getString("retmsg"));
        repData.put("riskListCode", riskList.getString("retcode"));
        retData.put("riskList", disposeYuShanReturnData(riskList, true));
        // 3：贷前风险报告接口
        JSONObject baiRongRequest = jieKouService.baiRong(ncmParams, "JF011" + ncmKeyWord, requestSn + "JF011");
        baiRongRequest = disposeBaiRongReturnData(baiRongRequest, requestSn, false);
        repData.put("riskSuggestCode", baiRongRequest.getString("retcode"));
        retData.put("riskSuggest", baiRongRequest);
        allMsg.append(" 贷前风险报告:" + baiRongRequest.getString("retmsg"));
        JSONObject data = new JSONObject();
        data.put("cert_no", cardNo);
        data.put("cert_name", name);
        data.put("mobile", mobile);
        // 全景雷达
        JSONObject panorama = zeWu2(new JieKou("JF027", "leida"), req_params, "JF027" + ncmKeyWord);
        panorama = disposeYuxinReturnData(panorama, requestSn, false);
        repData.put("panoramaCode", panorama.getString("retcode"));
        retData.put("panorama", panorama);
        allMsg.append(" 全景雷达:" + panorama.getString("retmsg"));
        // 未租凭分
        PersonalRentScoreRequest param = new PersonalRentScoreRequest();
        param.setIdCardNo(cardNo);
        param.setFullName(name);
        param.setMobile(mobile);
        param.setFileId("");
        JSONObject apply = juHe(new JieKou("JF026", "A3"), param, "JF026" + ncmKeyWord);
        apply = disposeJuHeReturnData(apply, requestSn, false);
        repData.put("applyCode", apply.getString("retcode"));
        retData.put("apply", apply);
        allMsg.append(" 申请意向-3C租赁:" + apply.getString("retmsg"));
        // 个人涉诉
        StudentVerifyRequest paramsv = new StudentVerifyRequest();
        paramsv.setIdCardNo(cardNo);
        paramsv.setFullName(name);
        JSONObject judicial = juHe(new JieKou("JF024", "A1"), paramsv, "JF024" + ncKeyWord);
        judicial = disposeJuHeReturnData(judicial, requestSn, false);
        repData.put("judicialCode", judicial.getString("retcode"));
        retData.put("judicial", judicial);
        allMsg.append(" 个人法院:" + judicial.getString("retmsg"));

        repData.put("allMsg", allMsg.toString());
        repData.put("retdata", retData);
        return repData;
    }

    @Override
    public JSONObject queryOverall(JSONObject req_params, JieKou jieKou, Merchant merchant) {
        // 查询
        String requestSn = req_params.getString("request_sn");

        String cardNo = req_params.getString("card_no");
        String name = req_params.getString("name");
        String mobile = req_params.getString("mobile");

        JSONObject ncParams = new JSONObject();
        ncParams.put("name", name);
        ncParams.put("cardNo", cardNo);
        String ncKeyWord = "::" + cardNo + "::" + name;

        JSONObject ncmParams = new JSONObject();
        ncmParams.put("name", name);
        ncmParams.put("cardNo", cardNo);
        ncmParams.put("mobile", mobile);
        String ncmKeyWord = "::" + cardNo + "::" + name + "::" + mobile;

        JSONObject cmParams = new JSONObject();
        cmParams.put("cardNo", cardNo);
        cmParams.put("mobile", mobile);

        JSONObject mParams = new JSONObject();
        mParams.put("mobile", mobile);
        String mKeyWord = "::" + mobile;
//        // 1：实名认证 / 手机三要素信息核验
        CompletableFuture<HashMap<String, JSONObject>> smrz_sjsys = CompletableFuture.supplyAsync(() -> {
            HashMap respMap = new HashMap<String, JSONObject>();
            JSONObject smrz = jieKouService.yuShan(ncParams, "JF005" + ncKeyWord, "PCB008", requestSn + "JF005");
            respMap.put("auth", disposeYuShanReturnData(smrz, true));
            JSONObject sjsys = jieKouService.yuShan(ncmParams, "JF007" + ncmKeyWord, "PCB151", requestSn + "JF007");
            respMap.put("verifier", disposeYuShanReturnData(sjsys, true));
            return respMap;
        });
        // 2 手机号在网时间 / 可信度查询V3
        CompletableFuture<HashMap<String, JSONObject>> telOnline_riskList = CompletableFuture.supplyAsync(() -> {
            HashMap respMap = new HashMap<String, JSONObject>();
            JSONObject telOnline = jieKouService.yuShan(mParams, "JF030" + mKeyWord, "MOB016", requestSn + "JF030");
            respMap.put("tel_time", disposeYuShanReturnData(telOnline, true));
            JSONObject riskList = jieKouService.yuShan(ncParams, "JF002" + ncKeyWord, "HRD016", requestSn + "JF002");
            respMap.put("risk_list", disposeYuShanReturnData(riskList, true));
            return respMap;
        });
        // 3：贷前风险报告接口
        CompletableFuture<JSONObject> baiRongRequest = CompletableFuture.supplyAsync(() -> {
            JSONObject data = jieKouService.baiRong(ncmParams, "JF011" + ncmKeyWord, requestSn + "JF011");
            return disposeBaiRongReturnDataV2(data, requestSn, false);
        });
        // 4: 全景雷达
        CompletableFuture<JSONObject> panorama = CompletableFuture.supplyAsync(() -> {
            JSONObject data = zeWu2(new JieKou("JF027", "leida"), req_params, "JF027" + ncmKeyWord);
            return disposeYuxinReturnDataV2(data, requestSn, false);
        });
        // 未租凭分 / 个人涉诉
        CompletableFuture<HashMap<String, JSONObject>> apply_judicial = CompletableFuture.supplyAsync(() -> {
            HashMap respMap = new HashMap<String, JSONObject>();

            PersonalRentScoreRequest param = new PersonalRentScoreRequest();
            param.setIdCardNo(cardNo);
            param.setFullName(name);
            param.setMobile(mobile);
            param.setFileId("");
            JSONObject apply = juHe(new JieKou("JF026", "A3"), param, "JF026" + ncmKeyWord);
            respMap.put("apply", disposeJuHeReturnDataV2(apply, requestSn, false));

            StudentVerifyRequest paramsv = new StudentVerifyRequest();
            paramsv.setIdCardNo(cardNo);
            paramsv.setFullName(name);
            JSONObject judicial = juHe(new JieKou("JF024", "A1"), paramsv, "JF024" + ncKeyWord);
            respMap.put("judicial", disposeJuHeReturnDataV2(judicial, requestSn, false));

            return respMap;
        });
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(smrz_sjsys, telOnline_riskList, baiRongRequest, panorama, apply_judicial);
//        CompletableFuture<Void> allFutures = CompletableFuture.allOf( apply_judicial, baiRongRequest, panorama);
        allFutures.join();
        JSONObject object = new JSONObject();
        try {
            object.putAll(smrz_sjsys.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.putAll(telOnline_riskList.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.putAll(apply_judicial.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("before_the_loan", baiRongRequest.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            object.put("panorama", panorama.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 记录
        ChargeRecord cr = new ChargeRecord(
                merchant.getMerchantCode(),
                requestSn,
                jieKou.getName(),
                name + "::" + cardNo + "::" + mobile,
                object.toJSONString(),
                jieKou.getUnitPrice(),
                merchant.getBalance().subtract(jieKou.getUnitPrice()),
                "完成"
        );
        // 扣费
        iMerchantService.debit(new Merchant(merchant.getMerchantCode(), jieKou.getUnitPrice()), cr);
        return object;
    }

    @Override
    public JSONObject yuShan(Map<String, Object> params, String keyWord, String prodId, String reqSn) {
        JSONObject redisRes = JSONObject.parseObject(redisTemplate.boundValueOps(keyWord).get());
        if (redisRes != null && !redisRes.isEmpty()) {
            redisRes.replace("request_sn", reqSn);
            return redisRes;
        }
        ProductDto productDto = new ProductDto();
        productDto.setProd_id(prodId);                       // 产品编号
        productDto.setReq_data(params);                      // 传入参数
        productDto.setRequest_sn(reqSn);                     // 商户唯一单号 请保证这个id唯一
        productDto.setReq_time(System.currentTimeMillis());  // 请求时间戳
        try {
            String jsonString = JSON.toJSONString(productDto);
            log.info("羽山请求：" + jsonString);
            String base64String = YushanAES.encode(jsonString, HEX_AES_128_PASSWORD);
            JSONObject jufaRes = JSONObject.parseObject(JuFaHttp.SendPost(base64String, TEST_URI, ACCOUNT_ID, HEX_AES_128_PASSWORD));
            log.info("羽山响应：" + jufaRes);
            if (!"PCB102".equals(prodId) && "000000".equals(jufaRes.getString("retcode"))) {
                redisTemplate.boundValueOps(keyWord).set(jufaRes.toJSONString(), 3, TimeUnit.DAYS);
            }
            return jufaRes;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject err = new JSONObject();
            err.put("retcode", 400000);
            err.put("retmsg", "数据处理异常！");
            return err;
        }
    }

    @Override
    public JSONObject baiRong(Map<String, Object> params, String keyWord, String reqSn) {
        JSONObject brRes = JSONObject.parseObject(redisTemplate.boundValueOps(keyWord).get());
        if (brRes != null && !brRes.isEmpty()) {
            return brRes;
        }
        MerchantServer ms = new MerchantServer();
        JSONObject jso = new JSONObject();
        jso.put("apiName", "strategyApi");
        JSONObject reqData = new JSONObject();
        reqData.put("strategy_id", "STR_BR0009626");
        reqData.put("id", com.br.client.util.Md5Utils.genMd5(params.get("cardNo").toString()));
        reqData.put("cell", com.br.client.util.Md5Utils.genMd5(params.get("mobile").toString()));
        reqData.put("name", params.get("name").toString());
        reqData.put("af_swift_number", reqSn);
        jso.put("reqData", reqData);
        log.info("百融请求：" + jso);
        try {
            String apiData = ms.getApiData(jso.toString());
            brRes = JSONObject.parseObject(apiData);
            log.info("百融响应：" + brRes);
            String code = brRes.getString("code");
            if ("100002".equals(code) || "00".equals(code)) {
                redisTemplate.boundValueOps(keyWord).set(brRes.toJSONString(), 3, TimeUnit.DAYS);
            }
            return brRes;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject err = new JSONObject();
            err.put("retcode", 400000);
            err.put("retmsg", "数据处理异常！");
            return err;
        }
    }

    @Override
    public JSONObject zeWu(JieKou jieKou, String type, JSONObject data, String key) {
        String up = jieKou.getSfCode();
        String jfCode = jieKou.getJfCode();
        if ("JF014".equals(jfCode)) {
            data.put("idcard", data.getString("cert_no"));
            data.put("name", data.getString("cert_name"));
            data.remove("cert_no");
            data.remove("cert_name");
        }
        if ("JF019".equals(jfCode)) {
            up += "1".equals(data.getString("type")) ? "/test" : "";
            data.remove("type");
        }
        log.info("zeWu预备参数" + "up:" + up + "  type:" + type + "  data:" + data + "  key:" + key);
        try {
            JSONObject brRes = JSONObject.parseObject(redisTemplate.boundValueOps(key).get());
            if (brRes != null && !brRes.isEmpty()) {
                return brRes;
            }
            JSONObject json = new JSONObject();
            json.put("token", "735822815bb64dd79f114b489213cd3c");
            json.put("timestamp", System.currentTimeMillis() + "");
            json.put("trans_id", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomStringUtils.randomNumeric(16));
            if (type != null) {
                json.put("type", type);
            }
            if ("JF015".equals(jfCode) || "JF023".equals(jfCode)) {
                // 生成授权书
                makeAccredit(data.getString("cert_name"), data.getString("cert_no"), data.getString("mobile"), "1");
                // 添加授权书url
                json.put("accessoryUrl", "http://jiekou.funishe.com/prod-api/jiekou/accredit/1");
            }

            log.info("则吾请求: " + data);
            String aes = JuFaHttp.encrypt("pFeNMTyFhNRzHrCtNPzc25S7HxtSaR3j", "6KJAG1ZJF63K161E66S3D7ZHN52NHFB5".substring(0, 16), data.toString());
            json.put("data", aes);
            String receive = JuFaHttp.send("https://www.zewubeidiao.com:8087/dataMiddle/api/" + up, json);
            log.info("则吾响应: " + receive);
            JSONObject receiveJs = JSONObject.parseObject(receive);
            if (receiveJs.getInteger("code") == 0) {
                redisTemplate.boundValueOps(key).set(receiveJs.toJSONString(), 3, TimeUnit.DAYS);
            }
            return receiveJs;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject err = new JSONObject();
            err.put("code", 400000);
            err.put("desc", "数据处理异常！");
            return err;
        }
    }

    @Override
    public JSONObject juHe(JieKou jieKou, Object param, String key) {
        //1.准备客户端
        JSONObject resp = JSON.parseObject(redisTemplate.boundValueOps(key).get());
        if (resp != null && !resp.isEmpty()) {
            return resp;
        }
        ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "1000003020240626", "ofSgvvRDQE7b2wwcPBAEFAK5Y8MC2Vg6");
        try {
            if ("A1".equals(jieKou.getSfCode())) {                // 个人涉诉标准版 个人涉诉（司法个人涉诉详情版）
                Result<LawSuitResponse> response = apiClient.personalLawSuit((StudentVerifyRequest) param);  //StudentVerifyRequest
                resp = JSON.parseObject(JSONObject.toJSONString(response));
            } else if ("A2".equals(jieKou.getSfCode())) {         // 个人涉诉详情版 个人诉讼记录（H文档-标准版个人涉诉全量模型）
                Result<LawSuitResponse> response = apiClient.personalLawSuitRecord((StudentVerifyRequest) param); // personalLawSuitRecord
//                if (response.getCode() == 200 && response.getData().getResultCode() ==1){
//                    response.getData().getDetail().set(0,response.getData().getDetail().getJSONObject(0).getJSONObject("lawsuitStat"));
//                }
                resp = JSON.parseObject(JSONObject.toJSONString(response));
            } else if ("A3".equals(jieKou.getSfCode())) {         // 未租凭分 租赁申请 （H产品接口文档-钜租分）
                Result<PersonalRentApplyResponse> response = apiClient.personalRentApply((PersonalRentScoreRequest) param);  //PersonalRentScoreRequest
                resp = JSON.parseObject(JSONObject.toJSONString(response));
            } else if ("A4".equals(jieKou.getSfCode())) {         // 婚姻状态
                Result<PersonalMarryResponse> response = apiClient.personalMarry((StudentVerifyRequest) param);  //PersonalRentScoreRequest
                resp = JSON.parseObject(JSONObject.toJSONString(response));
            } else if ("A5".equals(jieKou.getSfCode())) {         // 企业纳税信息
                Result<EnterpriseTaxAuthResponse> response = apiClient.taxAuthUrl((BaseRequest) param);         //EnterpriseTaxAuthResponse
                resp = JSON.parseObject(JSONObject.toJSONString(response));
            } else if ("A6".equals(jieKou.getSfCode())) {         // 公安不良
                Result<PersonalPublicSecurityResponse> response = apiClient.personalPublicSecurity((StudentVerifyRequest) param);  //StudentVerifyRequest
                resp = JSON.parseObject(JSONObject.toJSONString(response));
            }
            if (resp.getInteger("code") == 200 && !"A5".equals(jieKou.getSfCode())) {
//                redisTemplate.boundValueOps(key).set(resp.toJSONString(), 3, TimeUnit.DAYS);
            } else {
                log.error("巨合：", resp.toJSONString());
            }
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject err = new JSONObject();
            err.put("code", 400000);
            err.put("msg", "数据处理异常！");
            return err;
        }
    }

    @Override
    public JSONObject sourceTypeNum6(JieKou jieKou, JSONObject param, String key) {
        //1.准备客户端
        JSONObject resp = JSON.parseObject(redisTemplate.boundValueOps(key).get());
        if (resp != null && !resp.isEmpty()) {
            return resp;
        }
        try {
            resp = JSON.parseObject(dataPost("http://open.aiclouddata.cn/v1/assessment/dataverify", param));
            log.info(key, resp);
            if (resp.getInteger("code") == 200) {
                redisTemplate.boundValueOps(key).set(resp.toJSONString(), 3, TimeUnit.DAYS);
            }
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            resp = new JSONObject();
            resp.put("code", 400000);
            resp.put("message", "数据处理异常！");
            return resp;
        }
    }

    @Override
    public JSONObject zeWu2(JieKou jieKou, JSONObject param, String key) {
        //1.准备客户端
        JSONObject resp = JSONObject.parseObject(redisTemplate.boundValueOps(key).get());
        if (resp != null && !resp.isEmpty()) {
            return resp;
        }
        try {
            String query = getResult(jieKou.getSfCode(), param);
            resp = JSONObject.parseObject(query);
            if ("200".equals(resp.getString("code"))) {
                redisTemplate.boundValueOps(key).set(resp.toJSONString(), 2, TimeUnit.DAYS);
            }
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            resp = new JSONObject();
            resp.put("resp_code", "400000");
            resp.put("resp_data", null);
            resp.put("resp_msg", "数据处理异常！");
            return resp;
        }
    }

    @Override
    public JSONObject beiBuWan(JieKou jieKou, JSONObject param, String key, String requestSn) {
        //1.准备客户端
        String s = redisTemplate.boundValueOps(key).get();
        if (StringUtils.isNotEmpty(s)) {
            return JSON.parseObject(s);
        }
        JSONObject resp;
        try {
            String clientId = "17937465686";
            String clientSecret = "5520107e8a264e8d9d6e6b8950b6eb84";
            String pwd = "5091ad4363a643baa40bf859fed5fe72";
            JSONObject reqData = new JSONObject();
            reqData.put("clientId", clientId);
            reqData.put("clientSecret", clientSecret);
            reqData.put("reqNo", requestSn);

            String sign = clientId;
            if (param.containsKey("cardNo")) {
                String cardNo = param.getString("cardNo").replace("x", "X");
                sign += cardNo;  // 身份证号
                reqData.put("idCard", cardNo);
            }
            if (param.containsKey("name")) {
                sign += param.getString("name");    // 姓名
                reqData.put("name", param.getString("name"));
            }
            if (param.containsKey("mobile")) {
                sign += param.getString("mobile");  // 手机号
                reqData.put("mobile", param.getString("mobile"));
            }
            reqData.put("sign", Md5Utils.hash(sign + pwd));
            String query = dataPost("https://data.horizonvast.com/data-service/" + jieKou.getSfCode(), reqData);
//            String query = "{\"msg\":\"请求成功\",\"result\":{\"reasonType\":0,\"isPayed\":1,\"taskId\":\"1xhadebecbcu\",\"status\":1},\"code\":0}";
            resp = JSON.parseObject(query);
            if (resp.getInteger("code") == 0) {
                redisTemplate.boundValueOps(key).set(query, 1, TimeUnit.DAYS);
            }
            return resp;

        } catch (Exception e) {
            e.printStackTrace();
            resp = new JSONObject();
            resp.put("resp_code", "400000");
            resp.put("resp_data", null);
            resp.put("resp_msg", "数据处理异常！");
            return resp;
        }
    }

    @Override
    public JSONObject blackQuery(JSONObject req_params) {
        // 查询
        String requestSn = req_params.getString("request_sn");

        String name = req_params.getString("name");
        String cardNo = req_params.getString("card_no");
        String mobile = req_params.getString("mobile");
        String request_sn = req_params.getString("request_sn");

        JSONObject ncParams = new JSONObject();
        ncParams.put("name", name);
        ncParams.put("cardNo", cardNo);
        String ncKeyWord = "::" + cardNo + "::" + name;

        JSONObject ncmParams = new JSONObject();
        ncmParams.put("name", name);
        ncmParams.put("cardNo", cardNo);
        ncmParams.put("mobile", mobile);
        ncmParams.put("request_sn", request_sn);
        String ncmKeyWord = "::" + cardNo + "::" + name + "::" + mobile;

//        // 1 个人涉诉
        CompletableFuture<JSONObject> grsu = CompletableFuture.supplyAsync(() -> {
            StudentVerifyRequest paramsv = new StudentVerifyRequest();
            paramsv.setIdCardNo(cardNo);
            paramsv.setFullName(name);
            JSONObject judicial = juHe(new JieKou("JF025", "A2"), paramsv, "JF025" + ncKeyWord);
            return disposeJuHeReturnDataV2(judicial, requestSn, false);
        });

        // 2 网路诈骗数量
        CompletableFuture<JSONObject> wlzpsl = CompletableFuture.supplyAsync(() -> {
            JSONObject object = new JSONObject();
            int cl = cardNo.length();
            String name_ = "";
            try {
                name_ = URLEncoder.encode(name, UTF8);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String param = "name=" + name_ + "&cardNo=" + cardNo.substring(cl - 6, cl);
            String s = HttpUtils.sendGet("http://175.178.170.139:8093/system/black/inter?" + param);
            JSONArray array = JSON.parseArray(s);
            object.put("hit", !array.isEmpty());
            object.put("hitData", array);
            return object;
        });
        CompletableFuture<JSONObject> sjsys = CompletableFuture.supplyAsync(() -> {
            JSONObject d = beiBuWan(new JieKou("vast-base/v3/base3"), ncmParams, "JF081" + ncmKeyWord,requestSn);
            d = disposeBeiBuWan(d, request_sn, true);
            d = beiBuWanThreeEleConversion(d);
            return d;
        });

        // 3：贷前风险报告接口
        CompletableFuture<JSONObject> baiRongRequest = CompletableFuture.supplyAsync(() -> {
            JSONObject data = jieKouService.baiRong(ncmParams, "JF011" + ncmKeyWord, requestSn + "JF011");
            return disposeBaiRongReturnDataV2(data, requestSn, false);
        });

        CompletableFuture<Void> allFutures = CompletableFuture.allOf(grsu, wlzpsl, sjsys);
        allFutures.join();
        JSONObject object = new JSONObject();
        try {
            JSONObject sjsys_ = sjsys.get();
            JSONObject dttz = baiRongRequest.get();

            object.put("grss", grsu.get());
            object.put("wlzpsl", wlzpsl.get());
            object.put("sjsys", sjsys_);
            object.put("dttz", dttz);

//            22 55
            int fs = 45;
            if ("000000".equals(dttz.getString("retcode")) &&
                    "00".equals(dttz.getJSONObject("retdata").getString("code")) &&
                    "1".equals(dttz.getJSONObject("retdata").getJSONObject("flag").getString("riskstrategy"))
            ) {

                String final_weight = dttz.getJSONObject("retdata").getJSONObject("rule").getJSONObject("result").getString("final_weight");
                fs = 100 - Integer.parseInt(final_weight);
            }
            boolean eq = false;
            if ("000000".equals(sjsys_.getString("retcode"))) {
                String checkResult = sjsys_.getJSONObject("retdata").getString("checkResult");
                eq = "0".equals(checkResult);
            }

            if (fs > 79 && !eq) {
                fs = 50;
            }
            object.put("score", fs);
            object.put("suggest", "待议");

            if (fs > 55) {
                object.replace("suggest", "通过");
            } else if (fs < 21) {
                object.replace("suggest", "拒绝");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    public static JSONObject disposeYuShanReturnData(JSONObject returnData, Boolean delReq) {
        returnData.remove("version");
        returnData.remove("retdate");
        if (delReq) {
            returnData.remove("request_sn");
            returnData.remove("response_sn");
        }
        return returnData;
    }

    public static JSONObject disposeBaiRongReturnData(JSONObject returnData, String requestSn, Boolean delReq) {
        String code = returnData.getString("code");
        String msg = "100002".equals(code) || "00".equals(code) ? "查询成功" : "查询处理异常！";
        JSONObject baiRongReturnData = new JSONObject();
        if ("00".equals(code) || "100002".equals(code)) {
            baiRongReturnData.put("retdata", returnData);
            baiRongReturnData.put("retcode", "000000");
        } else {
            baiRongReturnData.put("retcode", code);
        }
        if (delReq) {
            baiRongReturnData.put("request_sn", requestSn);
            baiRongReturnData.put("response_sn", returnData.getString("swift_number"));
        }
        baiRongReturnData.put("retmsg", msg);
        return baiRongReturnData;
    }

    public JSONObject disposeZewuReturnData(JSONObject returnData, String requestSn, Boolean delReq) {
        Integer code = returnData.getInteger("code");
        if (code == 0) {
            returnData.put("retdata", returnData.get("data"));
            returnData.remove("data");
            returnData.put("retcode", "000000");
        } else if (code == -1) {
            returnData.put("retcode", "200000");
        } else if (code == 1) {
            returnData.put("retcode", "100000");
        } else if (code == 1000) {
            returnData.put("retcode", "err_012");
        } else {
            returnData.put("retcode", code.toString());
        }
        returnData.put("retmsg", returnData.getString("desc"));
        if (delReq) {
            returnData.put("request_sn", requestSn);
            returnData.put("response_sn", returnData.getString("trans_id"));
        }
        returnData.remove("code");
        returnData.remove("desc");
        returnData.remove("trans_id");
        return returnData;
    }

    public static JSONObject disposeJuHeReturnData(JSONObject returnData, String requestSn, Boolean delReq) {
        Integer code = returnData.getInteger("code");
        if (code == 200) {
            returnData.put("retdata", returnData.get("data"));
            returnData.remove("data");
            returnData.put("retcode", "000000");
        } else {
            returnData.put("retcode", code.toString());
        }
        returnData.put("retmsg", returnData.getString("msg"));
        if (delReq) {
            returnData.put("request_sn", requestSn);
            returnData.put("response_sn", requestSn);
        }
        returnData.remove("code");
        returnData.remove("msg");
        return returnData;
    }

    public JSONObject disposeSourceTypeNum6ReturnData(JSONObject returnData, String requestSn, Boolean delReq) {
        Integer code = returnData.getInteger("code");
        if (code == 200) {
            String data = returnData.getString("data");
            JSONValidator.Type jsonType = JSONValidator.from(data).getType();
            if (jsonType == JSONValidator.Type.Object) {
                returnData.put("retdata", JSON.parseObject(data));
            } else if (jsonType == JSONValidator.Type.Array) {
                returnData.put("retdata", JSON.parseArray(data));
            } else {
                returnData.put("retdata", returnData.get("data"));
            }
            returnData.put("retcode", "000000");
        } else {
            returnData.put("retcode", code.toString());
        }
        returnData.put("retmsg", returnData.getString("message"));
        if (delReq) {
            returnData.put("request_sn", requestSn);
            returnData.put("response_sn", requestSn);
        }
        returnData.remove("code");
        returnData.remove("message");
        returnData.remove("data");
        returnData.remove("requestLogId");
        return returnData;
    }

    public JSONObject disposeYuxinReturnData(JSONObject returnData, String requestSn, Boolean delReq) {
        String code = returnData.getString("code");

        returnData.put("retdata", returnData.get("data"));
        returnData.remove("data");
        returnData.put("retcode", "200".equals(code) ? "000000" : code);
        returnData.remove("code");
        returnData.put("retmsg", returnData.getString("message"));
        returnData.remove("message");
        if (delReq) {
            returnData.put("request_sn", requestSn);
        }
        return returnData;
    }

    public static JSONObject disposeBaiRongReturnDataV2(JSONObject returnData, String requestSn, Boolean delReq) {
        String code = returnData.getString("code");
        String msg = "100002".equals(code) || "00".equals(code) ? "查询成功" : "查询处理异常！";
        JSONObject baiRongReturnData = new JSONObject();
        if ("00".equals(code) || "100002".equals(code)) {
            if (returnData.containsKey("RiskStrategy")) {
                returnData.put("riskstrategy", returnData.getJSONObject("RiskStrategy"));
                returnData.remove("RiskStrategy");
            }
            if (returnData.containsKey("ApplyLoanStr")) {
                returnData.put("applyloanstr", returnData.getJSONObject("ApplyLoanStr"));
                returnData.remove("ApplyLoanStr");
            }
            if (returnData.containsKey("Rule")) {
                returnData.put("rule", returnData.getJSONObject("Rule"));
                returnData.remove("Rule");
            }
            if (returnData.containsKey("SpecialList_c")) {
                returnData.put("specialList_c", returnData.getJSONObject("SpecialList_c"));
                returnData.remove("SpecialList_c");
            }
            if (returnData.containsKey("Flag")) {
                returnData.put("flag", returnData.getJSONObject("Flag"));
                returnData.remove("Flag");
            }
            if (returnData.containsKey("ExecutionLimited")) {
                returnData.put("executionlimited", returnData.getJSONObject("ExecutionLimited"));
                returnData.remove("ExecutionLimited");
            }
            baiRongReturnData.put("retdata", returnData);
            baiRongReturnData.put("retcode", "000000");
        } else {
            baiRongReturnData.put("retcode", code);
        }
        if (delReq) {
            baiRongReturnData.put("request_sn", requestSn);
            baiRongReturnData.put("response_sn", returnData.getString("swift_number"));
        }
        baiRongReturnData.put("retmsg", msg);
        return baiRongReturnData;
    }

    public static JSONObject disposeJuHeReturnDataV2(JSONObject returnData, String requestSn, Boolean delReq) {
        String response_sn = null;
        Integer code = returnData.getInteger("code");
        if (code == 200) {
            JSONObject data = returnData.getJSONObject("data");
            response_sn = data.getString("requestId");

            data.put("result_code", data.getString("resultCode"));
            data.remove("requestId");
            data.remove("resultCode");

            returnData.put("retdata", data);
            returnData.put("retcode", "000000");
        } else {
            returnData.put("retcode", code.toString());
        }
        returnData.put("retmsg", returnData.getString("msg"));
        if (delReq) {
            returnData.put("request_sn", requestSn);
            returnData.put("response_sn", response_sn);
        }
        returnData.remove("code");
        returnData.remove("msg");
        returnData.remove("data");
        return returnData;
    }

    public JSONObject disposeYuxinReturnDataV2(JSONObject returnData, String requestSn, Boolean delReq) {
        returnData.put("retcode", "400000");
        returnData.put("retdata", returnData.get("data"));
        returnData.put("retmsg", returnData.getString("error"));
        JSONObject data = returnData.getJSONObject("data");
        if (data.containsKey("result")) {
            JSONObject result = data.getJSONObject("result");

            String code_ = result.getString("code");
            if (!"success".equals(code_)) {
                returnData.put("retcode", "400000");
            } else {
                returnData.put("retcode", "000000");
            }
            if (result.containsKey("respBody") &&
                    result.getJSONObject("respBody").containsKey("data") &&
                    result.getJSONObject("respBody").getJSONObject("data").containsKey("data") &&
                    result.getJSONObject("respBody").getJSONObject("data").getJSONObject("data").containsKey("data")
            ) {
                JSONObject data_ = result.getJSONObject("respBody").getJSONObject("data").getJSONObject("data").getJSONObject("data");
                returnData.put("retmsg", data_.getString("desc"));
            }
            data.getJSONObject("result").put("resp_body", data.getJSONObject("result").getJSONObject("respBody"));
            data.getJSONObject("result").put("resp_head", data.getJSONObject("result").getJSONObject("respHead"));
            data.getJSONObject("result").remove("respBody");
            data.getJSONObject("result").remove("respHead");
            returnData.replace("data", data);
        }
        if (delReq) {
            returnData.put("request_sn", requestSn);
            returnData.put("response_sn", data.getString("api_no"));
        }
        returnData.remove("code");
        returnData.remove("error");
        returnData.remove("data");
        return returnData;
    }

    public JSONObject disposeBeiBuWan(JSONObject returnData, String requestSn, Boolean delReq) {
        JSONObject data = new JSONObject();
        if (returnData.containsKey("resp_code")) {
            return returnData;
        } else if (returnData.getInteger("code") == 0) {
            data.put("retcode", "000000");
            if (returnData.containsKey("data")) {
                data.put("retdata", returnData.getJSONObject("data"));
            } else if (returnData.containsKey("result")) {
                data.put("retdata", returnData.getJSONObject("result"));
            }
        } else {
            data.put("retcode", "400000");
            data.put("retmsg", returnData.getString("msg"));
        }
        if (delReq) {
            data.put("request_sn", requestSn);
            data.put("response_sn", returnData.getString("seqNo"));
        }
        return data;
    }

    JSONObject beiBuWanTwoEleConversion(JSONObject data) {
//        System.out.println("beiBuWanTwoEleConversion：" + data);
        JSONObject retdata = JSON.parseObject("{\"final_valid_result\": \"0\"}");
        String retcode = data.getString("retcode");
        if (data.containsKey("retdata") && "000000".equals(retcode)) {
            Integer status = data.getJSONObject("retdata").getInteger("status");
            if (status == 0) {
                data.replace("retcode", "warn_001");
                data.remove("retdata");
                data.put("retmsg", "待定");
            } else if (status == 1) {
                data.replace("retdata", retdata);
                data.put("retmsg", "核验通过");
            } else if (status == 2) {
                data.replace("retcode", "warn_002");
                data.remove("retdata");
                data.put("retmsg", "核验不通过");
            } else if (status == 3) {
                data.replace("retcode", "warn_003");
                data.remove("retdata");
                data.put("retmsg", "查无此身份证");
            } else if (status == 4) {
                data.replace("retcode", "warn_002");
                data.remove("retdata");
                data.put("retmsg", "不一致");
            } else if (status == 7) {
                data.replace("retcode", "err_015");
                data.remove("retdata");
                data.put("retmsg", "获取失败");
            }
        }
        return data;
    }

    public JSONObject beiBuWanThreeEleConversion(JSONObject data) {
        JSONObject retdata = JSON.parseObject("{\"attribute_en\": \"\",\"province\": \"\",\"city\": \"\",\"attribute\": \"\", \"checkResult\": \"\"}");
//        System.out.println("beiBuWanThreeEleConversion：" + data);
        String retcode = data.getString("retcode");
        if ("000000".equals(retcode)) {
            JSONObject retdata_ = data.getJSONObject("retdata");
            if (10 == retdata_.getInteger("busiCode")) {
                JSONObject result = retdata_.getJSONObject("result");
                if (StringUtils.isNotEmpty(result.getString("province"))) {
                    retdata.replace("province", result.getString("province"));
                }
                if (StringUtils.isNotEmpty(result.getString("city"))) {
                    retdata.replace("city", result.getString("city"));
                }
                if (StringUtils.isNotEmpty(result.getString("isp"))) {
                    retdata.replace("attribute_en", result.getString("isp"));
                }
                String type = result.getString("type");
                retdata.replace("attribute", "1".equals(type) ? "移动" : "2".equals(type) ? "联通" : "3".equals(type) ? "电信" : "");

                int status = result.getIntValue("status");
                retdata.replace("checkResult", 1 == status ? "0" : 2 == status ? "1" : 3 == status ? "-1" : "");
            } else {
                data.put("retmsg", retdata_.getString("busiMsg"));
                data.replace("retcode", "err_012");
            }
            data.replace("retdata", retdata);
        } else {
            data.remove("retdata");
        }
        return data;
    }

}
